package com.poly.cms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.poly.cms.domain.CmsChannel;
import com.poly.cms.domain.CmsContent;
import com.poly.cms.mapper.CmsContentMapper;
import com.poly.cms.pojo.dto.CmsContentDTO;
import com.poly.cms.pojo.query.CmsChannelQuery;
import com.poly.cms.pojo.query.CmsContentQuery;
import com.poly.cms.pojo.vo.CmsChannelVO;
import com.poly.cms.pojo.vo.CmsContentVO;
import com.poly.cms.service.ICmsChannelService;
import com.poly.cms.service.ICmsContentService;
import com.poly.common.core.domain.R;
import com.poly.common.core.enums.CommonStatus;
import com.poly.common.core.tools.utils.Func;
import com.poly.common.core.tools.utils.StringUtil;
import com.poly.common.core.utils.ConvertUtils;
import com.poly.common.core.web.page.Pagination;
import com.poly.system.RemoteUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 内容基础Service业务层处理
 *
 * @author poly
 * @date 2023-10-25
 */
@Service
public class CmsContentServiceImpl extends ServiceImpl<CmsContentMapper, CmsContent> implements ICmsContentService {

    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private ICmsChannelService channelService;

    public LambdaQueryWrapper<CmsContent> getWrapper(CmsContentQuery query) {
        LambdaQueryWrapper<CmsContent> wrapper = null;
        if (Func.isNotEmpty(query)) {
            wrapper = Wrappers.<CmsContent>lambdaQuery();
            if (Func.isNotEmpty(query.getId())) {
                wrapper.eq(CmsContent::getId, query.getId());
            }
            if (Func.isNotEmpty(query.getTitle())) {
                wrapper.eq(CmsContent::getTitle, query.getTitle());
            }
            if (Func.isNotEmpty(query.getAuthor())) {
                wrapper.eq(CmsContent::getAuthor, query.getAuthor());
            }
            if (Func.isNotEmpty(query.getSource())) {
                wrapper.eq(CmsContent::getSource, query.getSource());
            }
            if (Func.isNotEmpty(query.getReadCount())) {
                wrapper.eq(CmsContent::getReadCount, query.getReadCount());
            }
            if (Func.isNotEmpty(query.getTop())) {
                wrapper.eq(CmsContent::getTop, query.getTop());
            }
            if (Func.isNotEmpty(query.getRecommend())) {
                wrapper.eq(CmsContent::getRecommend, query.getRecommend());
            }
            if (Func.isNotEmpty(query.getKeyword())) {
                wrapper.eq(CmsContent::getKeyword, query.getKeyword());
            }
            if (Func.isNotEmpty(query.getContent())) {
                wrapper.eq(CmsContent::getContent, query.getContent());
            }
            if (Func.isNotEmpty(query.getOpenMode())) {
                wrapper.eq(CmsContent::getOpenMode, query.getOpenMode());
            }
            if (Func.isNotEmpty(query.getChannelId())) {
                wrapper.eq(CmsContent::getChannelId, query.getChannelId());
            }
            if (Func.isNotEmpty(query.getAnnex())) {
                wrapper.eq(CmsContent::getAnnex, query.getAnnex());
            }
            if (Func.isNotEmpty(query.getStatus())) {
                wrapper.eq(CmsContent::getStatus, query.getStatus());
            }
        }
        return wrapper;
    }

    /**
     * 查询内容基础
     *
     * @param id 内容基础主键
     * @return 内容基础
     */
    @Override
    public CmsContent get(Long id) {
        return getById(id);
    }


    /**
     * 查询内容基础
     *
     * @param id 内容基础主键
     * @return 内容基础
     */
    @Override
    public CmsContentVO getVO(Long id) {
        CmsContentVO contentVO = Func.copyProperties(this.get(id), CmsContentVO.class);
        Map<Long, String> userNameMap = R.getData(remoteUserService.getUserNameMap(Arrays.asList(contentVO.getCreateBy(), contentVO.getUpdateBy())));
        if (Func.isNotEmpty(userNameMap)) {
            contentVO.setCreateByName(userNameMap.get(contentVO.getCreateBy()));
            contentVO.setUpdateByName(userNameMap.get(contentVO.getUpdateBy()));
        }

        contentVO.setStatusStr(CommonStatus.getName(contentVO.getStatus()));
        contentVO.setChannelName(channelService.get(contentVO.getChannelId()).getChannelName());
        if (StringUtil.isNotBlank(contentVO.getAnnex())) {
            String[] split = contentVO.getAnnex().split(",");
            contentVO.setAnnexList(Arrays.asList(split));
        }
        return contentVO;
    }

    public Pagination<CmsContentVO> queryPage(CmsContentQuery query) {
        if (Func.isEmpty(query.getChannelId()) || query.getChannelId() == 0) {
            List<CmsChannelVO> channelVOS = channelService.listTree(new CmsChannelQuery());
            query.setChannelId(channelVOS.get(0).getId());
        }
        IPage<CmsContent> page = baseMapper.selectPage(
                query.getPage(),
                getWrapper(query)
        );
        Pagination<CmsContentVO> pagination = Pagination.toPagination(page, CmsContentVO.class);
        if (Func.isNotEmpty(pagination.getRows())) {
            List<Long> userIds = pagination.getRows().stream().map(p -> p.getCreateBy()).collect(Collectors.toList());
            userIds.addAll(pagination.getRows().stream().map(p -> p.getUpdateBy()).collect(Collectors.toList()));
            List<Long> collect = userIds.stream().distinct().collect(Collectors.toList());
            Map<Long, String> userNameMap = R.getData(remoteUserService.getUserNameMap(collect));
            if (Func.isNotEmpty(userNameMap)) {
                pagination.getRows().forEach(i -> {
                    if (StringUtil.isNotBlank(i.getAnnex())) {
                        String[] split = i.getAnnex().split(",");
                        i.setAnnexList(Arrays.asList(split));
                    }
                    i.setCreateByName(userNameMap.get(i.getCreateBy()));
                    i.setUpdateByName(userNameMap.get(i.getUpdateBy()));
                    i.setStatusStr(CommonStatus.getName(i.getStatus()));
                    i.setChannelName(channelService.get(i.getChannelId()).getChannelName());
                });
            }
        }
        return pagination;

    }

    /**
     * 查询内容基础列表
     *
     * @param query 内容基础
     * @return 内容基础
     */
    @Override
    public List<CmsContentVO> queryList(CmsContentQuery query) {
        if (Func.isEmpty(query.getChannelId()) || query.getChannelId() == 0) {
            List<CmsChannelVO> channelVOS = channelService.listTree(new CmsChannelQuery());
            query.setChannelId(channelVOS.get(0).getId());
        }
        List<CmsContentVO> contentVOS = baseMapper.queryList(query);
        List<Long> userIds = contentVOS.stream().map(CmsContentVO::getCreateBy).collect(Collectors.toList());
        userIds.addAll(contentVOS.stream().map(CmsContentVO::getUpdateBy).collect(Collectors.toList()));
        List<Long> collect = userIds.stream().distinct().collect(Collectors.toList());
        Map<Long, String> userNameMap = R.getData(remoteUserService.getUserNameMap(collect));
        if (Func.isNotEmpty(userNameMap)) {
            contentVOS.forEach(i -> {
                if (StringUtil.isNotBlank(i.getAnnex())) {
                    String[] split = i.getAnnex().split(",");
                    i.setAnnexList(Arrays.asList(split));
                }
                i.setCreateByName(userNameMap.get(i.getCreateBy()));
                i.setUpdateByName(userNameMap.get(i.getUpdateBy()));
                i.setStatusStr(CommonStatus.getName(i.getStatus()));
                i.setChannelName(channelService.get(i.getChannelId()).getChannelName());
            });
        }
        return contentVOS;
    }

    /**
     * 新增内容基础
     *
     * @param dto 内容基础
     * @return 结果
     */
    @Override
    public boolean add(CmsContentDTO dto) {
        CmsContent entity = ConvertUtils.convert(dto, CmsContent.class);
        entity.setId(null);
        return save(entity);
    }

    /**
     * 修改内容基础
     *
     * @param dto 内容基础
     * @return 结果
     */
    @Override
    public boolean update(CmsContentDTO dto) {
        CmsContent entity = ConvertUtils.convert(dto, CmsContent.class);
        return updateById(entity);
    }

    /**
     * 批量删除内容基础
     *
     * @param ids 需要删除的内容基础主键
     * @return 结果
     */
    @Override
    public boolean deleteByIds(Long[] ids) {
        return removeBatchByIds(Arrays.asList(ids));
    }

    /**
     * 删除内容基础信息
     *
     * @param id 内容基础主键
     * @return 结果
     */
    @Override
    public boolean deleteById(Long id) {
        return removeById(id);
    }

    @Override
    public List<CmsContent> getByChannelId(Long channelId) {
        return this.list(new LambdaQueryWrapper<CmsContent>().eq(CmsContent::getChannelId, channelId));
    }

    @Override
    public List<CmsContentVO> getContentByEnglishName(String englishName) {
        CmsChannel channel = channelService.getOne(new LambdaQueryWrapper<CmsChannel>().eq(CmsChannel::getEnglishName, englishName));
        if (Func.isNull(channel)) return new ArrayList<>();
        return Func.copyProperties(this.list(new LambdaQueryWrapper<CmsContent>().eq(CmsContent::getChannelId, channel.getId())
                .eq(CmsContent::getStatus, CommonStatus.normal.getValue())), CmsContentVO.class);
    }
}
